import { createRouter, createWebHistory } from 'vue-router'
// import HomeView from '../views/HomeView.vue'
import { ElMessage } from 'element-plus'
const routes = [
  {
    // 布局的路由
    path: '/',
    name: 'layout',
    component: () => import('../views/index/index.vue'),
    // 重定向
    redirect: '/role',
    children: [
      {
        path: '/role',
        name: 'role',
        component: () => import('../views/role/index.vue')
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('../views/user/index.vue')
      },
      {
        path: '/menu',
        name: 'menu',
        component: () => import('../views/menu/index.vue')
      },
      {
        path: '/other',
        name: 'other',
        component: () => import('../views/other/index.vue')
      },

    ]
  },
  // 登录页可以写在外面
  {
    path: '/404',
    name: '404',
    component: () => import('../views/404/index.vue'),
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  }
  // {
  //   path: '/about',
  //   name: 'about',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  // }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 定义全局导航守卫
router.beforeEach((to, from, next) => {
  // 如果用户已经登录: 如果访问的是登录页，不让他进，跳转到首页； 如果访问其他页面，可以进
  // 如果用户未登录： 如果访问的是登录页，让他进； 如果访问的是其他页面，不让他进，并且跳转到登录页
  if (!localStorage.getItem('token')) {
    // 说明用户未登录
    if (to.path == '/login') {
      next()
    } else {
      ElMessage.error('请重新登录')
      next('/login')
    }
  } else {
    //说明用户已经登录
    if (to.path == '/login') {
      next('/')
    }
  }
  next()
})


export default router
